package com.lau.controller;

import cn.hutool.core.map.MapUtil;
import com.lau.common.lang.Result;
import com.lau.constant.CacheConstants;
import com.lau.utils.RedisUtil;
import com.wf.captcha.SpecCaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * @author:Lau
 * @create: 2023-11-07 13:41
 * @Description: 验证码
 */
@RestController
@Slf4j
public class CaptchaController {

    @Autowired
    RedisUtil redisUtil;

    @ResponseBody
    @GetMapping("/captcha")
    public Result captcha()  {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        String verCode = specCaptcha.text().toLowerCase();
        String key = UUID.randomUUID().toString();
        // 存入redis并设置过期时间为120秒
        redisUtil.hset(CacheConstants.CAPTCHA_CODE_KEY, key, verCode, 120);
        log.info("验证码 {}",verCode);
        // 将key和base64返回给前端
        return Result.succ(MapUtil.builder()
                .put("key", key).put("image", specCaptcha.toBase64()).map());
    }

}

